package com.sk.bilibili.tool;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.Session;
import lombok.SneakyThrows;

import java.io.BufferedReader;
import java.io.InputStream;

/**
 * @author 邵康
 * @date 2021/12/2 9:14
 */
public class updateJar {

    private static final String SRC_PATH = "E:\\IDEA\\BiliBiliWeb\\target\\bilibili-0.0.1-SNAPSHOT.jar";
    private static final String TAR_DIR = "/root/springboot/";
    private static final String HOST = "49.234.47.204";

    @SneakyThrows
    public static void main(String[] args) {
        Connection connection = createConnection();
        putFile(connection);
        execShell(connection,"cd springboot; sh bilibili.sh");//执行多行 语句
//        execShell(connection,"cd springboot; cat bilibili.log");
        connection.close();
    }

    @SneakyThrows
    private static void execShell(Connection connection,String cmd) {
        Session session = connection.openSession();
        session.execCommand(cmd);
        print(session.getStdout());
        print(session.getStderr());
        session.close();
    }

    @SneakyThrows
    private static void print(InputStream is) {
        byte[] bytes=new byte[1024];
        int len;
        while ((len=is.read(bytes))!=-1){
            System.out.println(new String(bytes,0,len));
        }
    }

    @SneakyThrows
    private static void putFile(Connection connection) {
        SCPClient client = connection.createSCPClient();
        client.put(SRC_PATH, TAR_DIR);
    }

    @SneakyThrows
    private static Connection createConnection() {
        Connection connection = new Connection(HOST, 22);
        connection.connect();
        if (!connection.authenticateWithPassword("root", "19981124@sk")) {
            throw new RuntimeException("无法连接到服务器");
        }
        return connection;
    }

}
